package com.lagou.rpc.consumer.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

/**
 * Rpc客户端处理类
 */
@ChannelHandler.Sharable
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable {

    //private ChannelHandlerContext ctx= null;
    private Channel channel = null;
    private String reqMsg = null;
    private String respMsg = null;

    public void setReqMsg(String reqMsg) {
        this.reqMsg = reqMsg;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }
    /**
     * 读取消息，返回远程调用结果
     * @param channelHandlerContext
     * @param msg
     * @throws Exception
     */
    @Override
    protected synchronized void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception{
        //返回远程响应结果，唤醒线程
        this.respMsg = msg;
        notify();
    }

    /**
     * 通道就绪事件
     * @param channelHandlerContext
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception {
        //this.ctx = channelHandlerContext;
    }

    /**
     * 远程调用提供者方法
     * @return
     */
    @Override
    public synchronized Object call() throws InterruptedException {
       this.channel.writeAndFlush(reqMsg);
       wait();
       return respMsg;
    }
}
